<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElInput, ElUpload, ElPagination, ElMessageBox, ElNotification, ElTag, ElSelect, ElOption, ElTooltip } from 'element-plus'
import { Search, Refresh, Download, Upload, Trash, FolderOpen, FileText, Filter, Check, Close, Eye, Edit, InfoFilled, Clock } from '@element-plus/icons-vue'

// 文件列表数据
const fileList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 上传对话框显示状态
const uploadDialogVisible = ref(false)
// 查看对话框显示状态
const viewDialogVisible = ref(false)
// 当前查看的文件
const currentFile = ref({})
// 筛选类型
const filterType = ref('all')
// 排序方式
const sortBy = ref('uploadTime')
const sortOrder = ref('descending')
// 上传文件列表
const uploadFiles = ref([])

// 加载文件列表
const loadFileList = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 模拟数据
    const fileTypes = ['文档', '图片', '视频', '音频', '压缩包', '其他']
    const mockData = Array.from({ length: 30 }, (_, index) => {
      const fileType = fileTypes[Math.floor(Math.random() * fileTypes.length)]
      const size = Math.floor(Math.random() * 1024 * 1024 * 10) // 0-10MB
      return {
        id: index + 1,
        name: `文件${index + 1}.${getFileExtension(fileType)}`,
        type: fileType,
        size: size,
        formattedSize: formatFileSize(size),
        uploadTime: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)),
        uploadBy: ['管理员', '张老师', '李老师', '王老师'][Math.floor(Math.random() * 4)],
        category: ['课程资料', '学生作业', '考试试卷', '教学计划', '其他'][Math.floor(Math.random() * 5)],
        downloadCount: Math.floor(Math.random() * 100),
        isPublic: Math.random() > 0.3
      }
    })

    // 筛选数据
    let filteredData = mockData
    if (searchKeyword.value) {
      filteredData = mockData.filter(item =>
        item.name.includes(searchKeyword.value) ||
        item.uploadBy.includes(searchKeyword.value) ||
        item.category.includes(searchKeyword.value)
      )
    }

    if (filterType.value !== 'all') {
      filteredData = filteredData.filter(item => item.type === filterType.value)
    }

    // 排序
    filteredData.sort((a, b) => {
      if (sortBy.value === 'uploadTime') {
        return sortOrder.value === 'descending' ? b.uploadTime - a.uploadTime : a.uploadTime - b.uploadTime
      } else if (sortBy.value === 'name') {
        return sortOrder.value === 'descending' ? b.name.localeCompare(a.name) : a.name.localeCompare(b.name)
      } else if (sortBy.value === 'size') {
        return sortOrder.value === 'descending' ? b.size - a.size : a.size - b.size
      } else if (sortBy.value === 'downloadCount') {
        return sortOrder.value === 'descending' ? b.downloadCount - a.downloadCount : a.downloadCount - b.downloadCount
      }
      return 0
    })

    // 分页
    total.value = filteredData.length
    fileList.value = filteredData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } catch (error) {
    ElNotification.error('获取文件列表失败')
    console.error('Failed to load file list:', error)
  } finally {
    loading.value = false
  }
}

// 获取文件扩展名
const getFileExtension = (fileType) => {
  const extensions = {
    '文档': ['doc', 'docx', 'pdf', 'txt', 'ppt', 'pptx', 'xls', 'xlsx'][Math.floor(Math.random() * 8)],
    '图片': ['jpg', 'jpeg', 'png', 'gif', 'bmp'][Math.floor(Math.random() * 5)],
    '视频': ['mp4', 'avi', 'mov', 'wmv'][Math.floor(Math.random() * 4)],
    '音频': ['mp3', 'wav', 'flac', 'ogg'][Math.floor(Math.random() * 4)],
    '压缩包': ['zip', 'rar', '7z', 'tar'][Math.floor(Math.random() * 4)],
    '其他': ['exe', 'dll', 'dat', 'bin'][Math.floor(Math.random() * 4)]
  }
  return extensions[fileType] || 'txt'
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) return `${size} B`
  else if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`
  else return `${(size / (1024 * 1024)).toFixed(2)} MB`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 搜索文件
const searchFiles = () => {
  currentPage.value = 1
  loadFileList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  filterType.value = 'all'
  currentPage.value = 1
  loadFileList()
}

// 上传文件
const handleUpload = async () => {
  try {
    // 模拟API上传延迟
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1500))

    // 模拟上传成功
    ElNotification.success('文件上传成功')
    uploadDialogVisible.value = false
    uploadFiles.value = []
    loadFileList()
  } catch (error) {
    ElNotification.error('文件上传失败')
    console.error('Failed to upload files:', error)
  } finally {
    loading.value = false
  }
}

// 打开上传对话框
const openUploadDialog = () => {
  uploadDialogVisible.value = true
}

// 关闭上传对话框
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
  uploadFiles.value = []
}

// 打开查看对话框
const openViewDialog = (row) => {
  currentFile.value = { ...row }
  viewDialogVisible.value = true
}

// 关闭查看对话框
const closeViewDialog = () => {
  viewDialogVisible.value = false
}

// 下载文件
const downloadFile = (row) => {
  ElNotification.info(`文件 ${row.name} 下载中...`)
  // 实际应用中这里应该实现文件下载功能
}

// 删除文件
const deleteFile = async (id) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该文件吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      // 删除数据
      fileList.value = fileList.value.filter(item => item.id !== id)
      total.value--
      ElNotification.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete file:', error)
    }
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadFileList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadFileList()
}

// 排序变化
const handleSortChange = (sortByVal, sortOrderVal) => {
  sortBy.value = sortByVal
  sortOrder.value = sortOrderVal
  loadFileList()
}

// 刷新数据
const refreshData = () => {
  loadFileList()
}

// 文件上传前检查
const beforeUpload = (file) => {
  // 这里可以添加文件类型和大小的检查
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 文件上传进度
const handleProgress = (event, file, fileList) => {
  // 可以在这里处理上传进度
}

// 文件状态变化
const handleChange = (file, fileList) => {
  uploadFiles.value = fileList
}

// 页面加载时获取数据
onMounted(() => {
  loadFileList()
})
</script>

<template>
  <div class="file-manager-container">
    <div class="header">
      <h2>文件管理</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入文件名、上传者或分类"
          prefix-icon="Search"
          style="width: 300px; margin-right: 10px;"
        />
        <el-select v-model="filterType" placeholder="文件类型" style="margin-right: 10px;">
          <el-option label="全部" value="all" />
          <el-option label="文档" value="文档" />
          <el-option label="图片" value="图片" />
          <el-option label="视频" value="视频" />
          <el-option label="音频" value="音频" />
          <el-option label="压缩包" value="压缩包" />
          <el-option label="其他" value="其他" />
        </el-select>
        <el-button type="primary" @click="searchFiles">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon> 上传
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button @click="showFilter">
          <el-icon><Filter /></el-icon> 筛选
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="fileList"
      style="width: 100%;"
      border
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="文件名" width="250" sortable="custom">
        <template #default="{ row }">
          <div class="file-name" @click="openViewDialog(row)">
            <el-icon :size="18" :class="getFileIconClass(row.type)">
              <FileText v-if="row.type === '文档'" />
              <FolderOpen v-else-if="row.type === '文件夹'" />
              <InfoFilled v-else />
            </el-icon>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="文件类型" width="100" align="center" />
      <el-table-column prop="formattedSize" label="大小" width="100" align="center" sortable="custom" />
      <el-table-column prop="uploadTime" label="上传时间" width="180" align="center" :formatter="formatDate" sortable="custom" />
      <el-table-column prop="uploadBy" label="上传者" width="120" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="downloadCount" label="下载次数" width="100" align="center" sortable="custom" />
      <el-table-column prop="isPublic" label="是否公开" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isPublic ? 'success' : 'danger'">
            {{ row.isPublic ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-tooltip content="查看">
            <el-button type="primary" size="small" @click.stop="openViewDialog(row)">
              <el-icon><Eye /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="下载">
            <el-button type="success" size="small" @click.stop="downloadFile(row)">
              <el-icon><Download /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除">
            <el-button type="danger" size="small" @click.stop="deleteFile(row.id)">
              <el-icon><Trash /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
      <el-upload
        ref="uploadRef"
        :headers="{ 'Content-Type': 'multipart/form-data' }"
        :multiple="true"
        :before-upload="beforeUpload"
        :on-progress="handleProgress"
        :on-change="handleChange"
        :file-list="uploadFiles"
        action=""
        :auto-upload="false"
      >
        <el-button type="primary" slot="trigger">
          <el-icon><Upload /></el-icon> 选择文件
        </el-button>
        <div slot="tip" class="el-upload__tip">
          支持多文件上传，单个文件不超过10MB
        </div>
      </el-upload>

      <div v-if="uploadFiles.length > 0" class="upload-file-list">
        <h4>已选择文件：</h4>
        <div v-for="file in uploadFiles" :key="file.uid" class="upload-file-item">
          <span>{{ file.name }}</span>
          <span>{{ formatFileSize(file.size) }}</span>
          <el-button type="text" size="small" @click="removeFile(file.uid)">
            <el-icon><Close /></el-icon> 移除
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeUploadDialog">取消</el-button>
        <el-button type="primary" @click="handleUpload">上传</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog v-model="viewDialogVisible" title="文件详情" width="600px">
      <div class="file-detail">
        <div class="file-header">
          <div class="file-icon-title">
            <el-icon :size="32" :class="getFileIconClass(currentFile.type)">
              <FileText v-if="currentFile.type === '文档'" />
              <FolderOpen v-else-if="currentFile.type === '文件夹'" />
              <InfoFilled v-else />
            </el-icon>
            <div class="file-title-detail">{{ currentFile.name }}</div>
          </div>
        </div>
        <div class="file-info">
          <div class="info-item">
            <span class="label">文件类型：</span>
            <span>{{ currentFile.type }}</span>
          </div>
          <div class="info-item">
            <span class="label">文件大小：</span>
            <span>{{ currentFile.formattedSize }}</span>
          </div>
          <div class="info-item">
            <span class="label">上传时间：</span>
            <span>{{ formatDate(currentFile.uploadTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">上传者：</span>
            <span>{{ currentFile.uploadBy }}</span>
          </div>
          <div class="info-item">
            <span class="label">分类：</span>
            <span>{{ currentFile.category }}</span>
          </div>
          <div class="info-item">
            <span class="label">下载次数：</span>
            <span>{{ currentFile.downloadCount }}</span>
          </div>
          <div class="info-item">
            <span class="label">是否公开：</span>
            <el-tag :type="currentFile.isPublic ? 'success' : 'danger'">
              {{ currentFile.isPublic ? '是' : '否' }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeViewDialog">关闭</el-button>
        <el-button type="primary" @click="downloadFile(currentFile)">下载</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.file-manager-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.file-name {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.file-name span {
  margin-left: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-file-list {
  margin-top: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.upload-file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.file-detail {
  padding: 10px 0;
}

.file-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.file-icon-title {
  display: flex;
  align-items: center;
}

.file-title-detail {
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
}

.file-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}
</style>